﻿using Microsoft.Extensions.Caching.Memory;
using System;

namespace Common
{
    /// <summary>
    /// 使用 .net core 2.0 新的内存缓存实现类的api
    /// </summary>
    public class httpCacheHelper
    {

        /// <summary>
        /// 默认的缓存实现类
        /// </summary>
        static MemoryCache cache = new MemoryCache(new MemoryCacheOptions());

        /// <summary>
        /// 获取缓存值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T getCache<T>(string key) where T : new()
        {
            if (!string.IsNullOrWhiteSpace(key) && cache.TryGetValue(key, out T val))
            {
                return val;
            }
            else
            {
                return default(T);
            }
        }

        /// <summary>
        /// 添加缓存内容
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="minutes"></param>
        public static void setCache(string key, object value, int minutes = 60)
        {
            if (!string.IsNullOrWhiteSpace(key))
            {
                cache.Set(key, value, new MemoryCacheEntryOptions
                {
                    SlidingExpiration = TimeSpan.FromMinutes(minutes)
                });
            }
        }

        /// <summary>
        /// 移除
        /// </summary>
        /// <param name="key"></param>
        public static void RemoveCacheByKey(string key)
        {
            if (!string.IsNullOrWhiteSpace(key))
            {
                cache.Remove(key);
            }
        }

    }
}
